import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import path from 'path'

// https://vitejs.dev/config/
export default ({ mode }) => {
  const pathSrc = path.resolve(__dirname, 'src')
  const VITE_APP_SERVER_URL: string = loadEnv(mode, process.cwd()).VITE_APP_PROXY_TARGET;
  const VITE_APP_BASE_URL: string = loadEnv(mode, process.cwd()).VITE_APP_PROXY_TARGET;
  const PROXY_TARGET = VITE_APP_SERVER_URL ? VITE_APP_SERVER_URL : VITE_APP_BASE_URL
  return defineConfig({
    base: './',
    resolve: {
      // 别名
      alias: {
        '@': pathSrc,
        '@g': `${pathSrc}/global`,
      },
    },
    server: {
      // 端口号
      port: 5179,
      // 配置跨域
      proxy: {
        '/api': {
          target: PROXY_TARGET, // 实际请求地址
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    // 插件
    plugins: [
      vue(),
      vueSetupExtend(),
      AutoImport({
        imports: ['vue'], // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        // 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
        resolvers: [
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({ prefix: 'Icon', }),
        ],
        dts: path.resolve(pathSrc, 'auto-imports.d.ts')
      }),
      Components({
        resolvers: [
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
        ],
        dts: path.resolve(pathSrc, 'components.d.ts')
      }),
      Icons({ autoInstall: true })
    ]
  })
}